/**
 * 关联词
 */

var Wechat = require('../../models/wechat/scrapyModel').Wechat;
var WechatStat = require('../../models/wechat/statModel').WechatStat;
var Keyword = require('../../models/keywordsModel').Keyword;
var Util = require('../../util/util');
var Spare = require('../../util/spareData');

//global variate
var wHash = new Util.HashMap(),fHash = new Util.HashMap();
wHash = initPublic();
fHash = initFilter();

function main(){
    console.log('微信 关联词 统计 开始');
    FindAllKeywords();
}
function initPublic(){
    //微信公众号类型映射 hash赋值
    console.log('公众号类型映射');
    var wechat_type = Spare.wechatSpare.wechat_type;
    var wHash = new Util.HashMap();
    for (var i in wechat_type) {
        for (var j in wechat_type[i]) {
            wHash.Set(wechat_type[i][j], i);
        }
    }
    return wHash;
}

function initFilter(){
    //过滤词表 hash赋值
    console.log('过滤词表映射');
    var filterKeywords = Spare.wechatSpare.filterKeywords;
    var fHash = new Util.HashMap();
    for (var i in filterKeywords) {
        fHash.Set(filterKeywords[i], filterKeywords[i]);
    }
    return fHash;
}

function FindAllKeywords(){
    Keyword.findAllKeywords(function (err, docs) {
        var list = [];
        if (err) {
            console.log(err);
        }
        for (var i in docs) {
            list.push({
                'keyword_id': docs[i]._id,
                'title': docs[i].title
            })
        }
        ListForEach(list,function(){
            console.log('===============  微信 关联词 统计 所有完成了！！');
        })

    });
}

function ListForEach(list,callback){
    var i,getTitle,findByTitle,consistPair,distinctPair,initExport,insertStat,next,done;
    i = 0;

    getTitle = function(){
        if(i>=list.length){
            return done();
        }
        console.log('获取题目...'+list[i].title);
        findByTitle(list[i]);
    };

    findByTitle = function(list){
        Wechat.findByKeyword(list.title,function(err,data){
            console.log('获取'+list.title+'的数据长度....'+data.length);
            consistPair(list,data);
        });
    };

    consistPair = function(list,data){
        console.log('组织pairs...'+list.title);
        var consistPairs = {
            'dianshitai': [],
            'shipinwangzhan': [],
            'jiemu': [],
            'menhuwangzhan': [],
            'zhuanyemeiti': [],
            'zhimei': [],
            'pinpai': [],
            'zimeiti': []
        };

        for(var d in data){
            var author = data[d].author,
                keywords = data[d].keywords;
            if(wHash.Contains(author)){
                //该账号author 是映射表中一员
                var len = keywords.length, a, b,str;
                if(len>0){
                    for(a = 0; a < len; a++){
                        //过滤keyword[a]
                        if(!fHash.Contains(keywords[a])){
                            for(b=a+1; b<len; b++){
                                //过滤keyword[b]
                                if(!fHash.Contains(keywords[b])){
                                    //组词 映射
                                    str = keywords[a]+'-'+keywords[b];
                                    consistPairs[wHash.Get(author)].push(str);
                                }
                            }
                        }
                    }
                }
            }
        }
        distinctPair(list,consistPairs);
    };

    distinctPair = function(list,consistPairs){
        console.log('去重pairs...'+list.title);
        var p,
            len,
            tHash = new Util.HashMap(),
            distinctPairs = {
                'dianshitai': {},
                'shipinwangzhan': {},
                'jiemu': {},
                'menhuwangzhan': {},
                'zhuanyemeiti': {},
                'zhimei': {},
                'pinpai': {},
                'zimeiti': {}
            };

        for (var t in consistPairs) {
            for (p = 0, len = consistPairs[t].length; p < len; p++) {
                if (!tHash.Contains(consistPairs[t][p]) && consistPairs[t][p] != '') {
                    //not exist
                    tHash.Set(consistPairs[t][p], consistPairs[t][p]);
                    distinctPairs[t][consistPairs[t][p]] = 1
                }
                else {
                    //exit
                    distinctPairs[t][consistPairs[t][p]]++;
                }
            }
        }
        initExport(list,distinctPairs);
    };

    initExport = function(list,dist){
        console.log('排序输出...'+list.title);
        var exportData = {
            'dianshitai': [],
            'shipinwangzhan': [],
            'jiemu': [],
            'menhuwangzhan': [],
            'zhuanyemeiti': [],
            'zhimei': [],
            'pinpai': [],
            'zimeiti': []
        };
        var index, k1, k2, weight,bubbleLen,count=0;
        for (var m in dist) {
            var arrw = [], arrk = [], bubble = {};
            for (var n in dist[m]) {
                if (dist[m][n]) {
                    arrk.push(n);
                    arrw.push(dist[m][n]);
                }
                bubble = Util.DoubleBubbleSort(arrw, arrk);
            }


            if (bubble.arr2) {
                bubbleLen = bubble.arr2.length;
                count = (bubbleLen > 10)
                    ? 10
                    : bubble;
                for (var bb = 0; bb < bubbleLen; bb++) {
                    if (bubble.arr2[bb]) {
                        index = bubble.arr2[bb].indexOf('-');
                        k1 = bubble.arr2[bb].substring(0, index);
                        k2 = bubble.arr2[bb].substring(index + 1);
                        weight = bubble.arr1[bb];
                        exportData[m].push({
                            'keyword1': k1,
                            'keyword2': k2,
                            'weight': weight
                        })
                    }
                }
            }
        }
        var exportData2 = [];
        exportData2.push(exportData);
        insertStat(list,exportData2);
    };

    insertStat = function(list,exportData){
        //console.log(exportData);
        WechatStat.saveRelateWords(list.keyword_id,list.title,exportData);
        next(list);
    };

    next = function(list){
        console.log('已经完成啦....'+list.title);
        ++i;
        getTitle();
    };

    done = function(){
        callback();
    };

    return getTitle();
}

exports.main = main;

